package com.example.cloud.service.business.medical.impl;

import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.medical.ExecuteRecordRepository;
import com.example.cloud.dao.business.medical.TreatPlanCourseDetailsRepository;
import com.example.cloud.model.basic.Project;
import com.example.cloud.model.business.medical.ExecuteRecord;
import com.example.cloud.model.business.medical.TreatPlanCourseDetails;
import com.example.cloud.service.business.medical.ExecuteService;
import com.example.cloud.service.business.medical.TreatPlanCourseDetailsService;
import com.example.cloud.utils.BusinessUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class TreatPlanCourseDetailsServiceImpl implements TreatPlanCourseDetailsService {

    private static final Logger logger = Logger.getLogger(TreatPlanCourseDetailsServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private ExecuteService executeService;

    @Autowired
    private ExecuteRecordRepository executeRecordRepository;

    @Autowired
    private TreatPlanCourseDetailsRepository treatPlanCourseDetailsRepository;

    @Override
    public TreatPlanCourseDetails findOne(Long id) {
        return treatPlanCourseDetailsRepository.findOne(id);
    }

    @Override
    @Transactional
    public TreatPlanCourseDetails doSave(TreatPlanCourseDetails record) {
        if(record.getId() == null){
            record.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            record.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PROJECT);
        }
        record.setCreationTime(null);
        BusinessUtil.appendRecord(record);
        return treatPlanCourseDetailsRepository.save(record);
    }

    @Override
    @Transactional
    public void batchInsert(List<TreatPlanCourseDetails> records) {
        for (TreatPlanCourseDetails record : records) {
            record.setId(null);
            record.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            record.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PROJECT);
            record.setTotalPrice(record.getPrice().multiply(new BigDecimal(record.getQuantity())));
            record.setCreationTime(null);
            BusinessUtil.appendRecord(record);
        }
        treatPlanCourseDetailsRepository.save(records);
    }

    @Override
    @Transactional
    public void doDeleteById(Long id) {
        // 逻辑删除
        treatPlanCourseDetailsRepository.delete(id);
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 逻辑删除
        StringBuilder sql = new StringBuilder("update treat_plan_course_details set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
    }

    @Override
    @Transactional
    public void doExecute(TreatPlanCourseDetails record, int status, String content) {
        // 执行次数+1
        if(status == StateConstants.EXECUTE_STATUS_YES) {
            record.setExecute(record.getExecute() + 1);
        }
        ExecuteRecord executeRecord = new ExecuteRecord();
        executeRecord.setPatientId(record.getPatientId());
        executeRecord.setComplaintId(record.getComplaintId());
        executeRecord.setOrderId(record.getId());
        executeRecord.setStatus(status);
        executeRecord.setTreatType(StateConstants.EXECUTE_TREAT_TYPE_COURSE);
        executeRecord.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PROJECT);
        executeRecord.setItemId(record.getItemId());
        executeRecord.setItemName(record.getItemName());
        executeRecord.setDoctorName(record.getCreatedBy());
        executeRecord.setDoctorRemark(record.getMedicalAdvice());
        executeRecord.setSource(record.getCourseName());
        executeRecord.setTotalCount(record.getQuantity());
        executeRecord.setLaveCount(record.getQuantity() - record.getExecute());
        executeRecord.setMedicalTime(record.getCreationTime());
        executeRecord.setExecuteContent(content);
        executeRecord.setCreationTime(null);
        BusinessUtil.appendRecord(executeRecord);
        executeService.doSave(executeRecord);
        // 更新已执行次数
        if(status == StateConstants.EXECUTE_STATUS_YES){
            record.setExecuteStatus(StateConstants.EXECUTE_STATUS_YES);
            BusinessUtil.appendRecord(record);
            treatPlanCourseDetailsRepository.save(record);
        }
    }

    @Override
    public List<TreatPlanCourseDetails> findByCourseId(Long courseId) {
        return treatPlanCourseDetailsRepository.findByCourseIdAndDeleteFlag(courseId, 0);
    }

    @Override
    @Transactional
    public void doStop(Long id) {
        TreatPlanCourseDetails details = treatPlanCourseDetailsRepository.findOne(id);
        details.setStatus(StateConstants.HOME_DETAILS_STATUS_STOP);
        details.setStopTime(new Date());
        BusinessUtil.appendRecord(details);
        treatPlanCourseDetailsRepository.save(details);
    }

    @Override
    @Transactional
    public List<TreatPlanCourseDetails> doReplace(Long id, List<Project> list) {
        // 更新原记录
        TreatPlanCourseDetails details = treatPlanCourseDetailsRepository.findOne(id);
        details.setStatus(StateConstants.HOME_DETAILS_STATUS_REPLACE);
        BusinessUtil.appendRecord(details);
        treatPlanCourseDetailsRepository.save(details);
        // 生成新记录
        for (Project project : list) {
            TreatPlanCourseDetails cd = new TreatPlanCourseDetails();
            cd.setPatientId(details.getPatientId());
            cd.setMemberId(details.getMemberId());
            cd.setComplaintId(details.getComplaintId());
            cd.setCourseId(details.getCourseId());
            cd.setCourseName(details.getCourseName());
            cd.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PROJECT);
            cd.setItemId(project.getId());
            cd.setItemName(project.getName());
            cd.setQuantity(project.getQuantity());
            cd.setPrice(project.getPrice());
            cd.setTotalPrice(project.getPrice().multiply(new BigDecimal(project.getQuantity())));
            cd.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            BusinessUtil.appendRecord(cd);
            treatPlanCourseDetailsRepository.save(cd);
        }
        // 返回变更后的数据
        return treatPlanCourseDetailsRepository.findByCourseIdAndDeleteFlag(details.getCourseId(),0);
    }
}
